﻿#region License

// Created by John Batte on 03/22/2012 at 7:16 AM.
// Last code cleanup: 03/22/2012 at 8:02 AM.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Diagnostics;

namespace BatteCode.Fx.ExceptionHandling
{
	/// <summary>
	/// 	Runs delegates within try-catch blocks, thus reducing the amount of repetitive code required to handle exceptions.
	/// </summary>
	public static class Try
	{
		static Try()
		{
			HandleErrors.DefaultStrategy = exception =>
			{
				Debug.WriteLine(exception.Message);
				Debug.WriteLine(exception.StackTrace);
				return new ExceptionState(exception, true);
			};
		}

		/// <summary>
		/// 	Gets the result of the specified value retriever.
		/// </summary>
		/// <typeparam name="TValue"> The type of the value. </typeparam>
		/// <param name="retriever"> The retriever. </param>
		/// <param name="errorHandler"> The error handler. </param>
		/// <returns> The result of the retriever, or the default value if an exception is thrown but handled. </returns>
		public static TValue Get<TValue>(Func<TValue> retriever, Func<Exception, ExceptionState> errorHandler = null)
		{
			try
			{
				return retriever();
			}
			catch (Exception exception)
			{
				Func<Exception, ExceptionState> handler = errorHandler ?? HandleErrors.DefaultStrategy;
				ExceptionState state = handler(exception);
				if (state.IsHandled) return default(TValue);
				throw;
			}
		}

		/// <summary>
		/// 	Executes the specified action.
		/// </summary>
		/// <param name="action"> The action. </param>
		/// <param name="errorHandler"> The error handler. </param>
		public static void Do(Action action, Func<Exception, ExceptionState> errorHandler = null)
		{
			try
			{
				action();
			}
			catch (Exception exception)
			{
				Func<Exception, ExceptionState> handler = errorHandler ?? HandleErrors.DefaultStrategy;
				ExceptionState state = handler(exception);
				if (state.IsHandled) return;
				throw;
			}
		}

		#region Nested type: HandleErrors

		/// <summary>
		/// 	Encapsulates the <see cref="Try" /> class's error-handling strategy.
		/// </summary>
		public static class HandleErrors
		{
			/// <summary>
			/// 	Gets or sets the default strategy.
			/// </summary>
			/// <value> The default strategy. </value>
			public static Func<Exception, ExceptionState> DefaultStrategy{ get; set; }
		}

		#endregion
	}
}